<template>
  <el-card shadow="never">
    <div slot="header" class="flex justify-between">
      <span class="text-sm">订单统计</span>
      <div>
        <el-check-tag
          style="margin-right: 8px"
          v-for="(item, index) in options"
          :key="index"
          :checked="current === item.value"
          @click="handleChoose(item.value)"
          >{{ item.text }}</el-check-tag
        >
      </div>
    </div>
    <!-- card body -->
    <el-divider />
    <div id="chart" ref="el" style="width: 100%; height: 300px"></div>
  </el-card>
</template>

<script setup>
  import { ref, onMounted, onUnmounted } from 'vue'
  import * as echarts from 'echarts'
  import { getStatistics3 } from '@/api/index.js'
  import { useResizeObserver } from '@vueuse/core'

  const options = [
    { text: '近一个月', value: 'month' },
    { text: '近一周', value: 'week' },
    { text: '近24小时', value: 'hour' },
  ]

  const current = ref('week')
  let myChart = null
  onMounted(() => {
    myChart = document.querySelector('#chart')
    if (myChart) {
      myChart = echarts.init(myChart)
      getData()
    }
  })

  function getData() {
    let option = {
      xAxis: {
        type: 'category',
        data: [],
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          data: [],
          type: 'bar',
          showBackground: true,
          backgroundStyle: {
            color: 'rgba(180, 180, 180, 0.2)',
          },
        },
      ],
    }

    myChart.showLoading()
    getStatistics3(current.value)
      .then((res) => {
        option.xAxis.data = res.data.x
        option.series[0].data = res.data.y
        myChart.setOption(option)
      })
      .finally(() => myChart.hideLoading())
  }

  function handleChoose(type) {
    current.value = type
    getData()
  }

  onUnmounted(() => {
    myChart && myChart.dispose()
  })

  const el = ref(null)
  useResizeObserver(el, (entries) => {
    myChart && myChart.resize()
  })
</script>

<style scoped></style>
